#!/bin/bash

BACKEND_DIR="./backend"
FRONTEND_DIR="./frontend"
LOG_DIR="./logs"
BACKEND_LOG="$LOG_DIR/backend.log"
FRONTEND_LOG="$LOG_DIR/frontend.log"
PID_FILE="./dst_management.pid"

start_services() {
  mkdir -p "$LOG_DIR"

  echo "启动 Flask 后端..."
  nohup python3 "$BACKEND_DIR/main.py" > "$BACKEND_LOG" 2>&1 &
  BACK_PID=$!

  echo "启动前端 HTTP 服务..."
  cd "$FRONTEND_DIR"
  nohup python3 -m http.server 5050 > "../$FRONTEND_LOG" 2>&1 &
  FRONT_PID=$!
  cd - >/dev/null

  echo "$BACK_PID" > "$PID_FILE"
  echo "$FRONT_PID" >> "$PID_FILE"

  echo "✅ 服务已启动"
  echo "前端地址：http://115.190.86.189:5050"
}

stop_services() {
  if [ -f "$PID_FILE" ]; then
    while read pid; do
      echo "停止进程 $pid..."
      kill -9 "$pid" >/dev/null 2>&1
    done < "$PID_FILE"
    rm -f "$PID_FILE"
    echo "🛑 所有服务已停止"
  else
    echo "⚠️ 没有正在运行的服务"
  fi
}

case "$1" in
  start)
    start_services
    ;;
  stop)
    stop_services
    ;;
  restart)
    stop_services
    sleep 1
    start_services
    ;;
  *)
    echo "用法: ./dst_management.sh {start|stop|restart}"
    ;;
esac
